/*  Some of this code is based on example Java application provided with JavaDB-Derby framework - SimpleApp.java*/
/* Author: James Owen : 19-Apr-2008 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.Properties;

/**
 * @author Ben Morrall
 * @version 0.2, 14 May 2008, Code Format, blm
 */
public class BuildUniLearnDB
{
	/* the default framework is embedded */
	private String framework = "embedded";
	private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
	private String protocol = "jdbc:derby:";

	public static void main(String[] args)
	{
		new BuildUniLearnDB().go(args);
		System.out.println("BuildUniLearnDB finished");
	}

	void go(String[] args)
	{
		/* parse the arguments to determine which framework is desired */
		parseArguments(args);

		System.out.println("SimpleApp starting in " + framework + " mode");

		/* load the desired JDBC driver */
		loadDriver();

		Connection conn = null;

		ArrayList statements = new ArrayList(); // list of Statements, PreparedStatements

		Statement s = null;
		ResultSet rs = null;
		try
		{
			Properties props = new Properties(); // connection properties

			// props.put("user", "unilearnApp");
			// props.put("password", "unilearnApp");

			String dbName = "testDB"; // the name of the database
			conn = DriverManager.getConnection(protocol + dbName + ";create=true", props);

			System.out.println("Connected to and created database " + dbName);

			System.out.println("Adding Subjects to DB");
			XMLReader xmlrdr = new XMLReader(conn, "unilearnData.xml");
			xmlrdr.parseFile();
			for (int i = 0; i < xmlrdr.getStatements().size(); i++)
			{
				try
				{
					xmlrdr.getStatements().get(i).execute();
				}
				catch (SQLException sxc)
				{
					printSQLException(sxc);
				}
			}
			for (int i = 0; i < xmlrdr.getStatements().size(); i++)
			{
				if (xmlrdr.getStatements().get(i) != null)
				{
					xmlrdr.getStatements().get(i).close();
				}
			}

			if (framework.equals("embedded"))
			{
				try
				{
					// the shutdown=true attribute shuts down Derby
					DriverManager.getConnection("jdbc:derby:;shutdown=true");
				}
				catch (SQLException se)
				{
					if (((se.getErrorCode() == 50000) && ("XJ015".equals(se.getSQLState()))))
					{
						System.out.println("Derby shut down normally");
					}
					else
					{
						System.err.println("Derby did not shut down normally");
						printSQLException(se);
					}
				}
			}
		}
		catch (SQLException sqle)
		{
			printSQLException(sqle);
		}
		finally
		{
			try
			{
				if (rs != null)
				{
					rs.close();
					rs = null;
				}
			}
			catch (SQLException sqle)
			{
				printSQLException(sqle);
			}

			// Statements and PreparedStatements
			int i = 0;
			while (!statements.isEmpty())
			{
				// PreparedStatement extend Statement
				Statement st = (Statement) statements.remove(i);
				try
				{
					if (st != null)
					{
						st.close();
						st = null;
					}
				}
				catch (SQLException sqle)
				{
					printSQLException(sqle);
				}
			}

			// Connection
			try
			{
				if (conn != null)
				{
					conn.close();
					conn = null;
				}
			}
			catch (SQLException sqle)
			{
				printSQLException(sqle);
			}
		}
	}

	private void loadDriver()
	{

		try
		{
			Class.forName(driver).newInstance();
			System.out.println("Loaded the appropriate driver");
		}
		catch (ClassNotFoundException cnfe)
		{
			System.err.println("\nUnable to load the JDBC driver " + driver);
			System.err.println("Please check your CLASSPATH.");
			cnfe.printStackTrace(System.err);
		}
		catch (InstantiationException ie)
		{
			System.err.println("\nUnable to instantiate the JDBC driver " + driver);
			ie.printStackTrace(System.err);
		}
		catch (IllegalAccessException iae)
		{
			System.err.println("\nNot allowed to access the JDBC driver " + driver);
			iae.printStackTrace(System.err);
		}
	}

	public static void printSQLException(SQLException e)
	{
		while (e != null)
		{
			System.err.println("\n----- SQLException -----");
			System.err.println("  SQL State:  " + e.getSQLState());
			System.err.println("  Error Code: " + e.getErrorCode());
			System.err.println("  Message:    " + e.getMessage());
			e = e.getNextException();
		}
	}

	private void parseArguments(String[] args)
	{
		if (args.length > 0)
		{
			if (args[0].equalsIgnoreCase("jccjdbcclient"))
			{
				framework = "jccjdbc";
				driver = "com.ibm.db2.jcc.DB2Driver";
				protocol = "jdbc:derby:net://localhost:1527/";
			}
			else if (args[0].equalsIgnoreCase("derbyclient"))
			{
				framework = "derbyclient";
				driver = "org.apache.derby.jdbc.ClientDriver";
				protocol = "jdbc:derby://localhost:1527/";
			}
		}
	}
}
